#include "DebugConfig.h"
#include <fstream>
#include <algorithm>
#include <cctype>

using namespace algo;

// Helper function to trim whitespace from a string
static void trim(std::string& s) 
{
    s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](unsigned char ch) {
        return !std::isspace(ch);
    }));
    s.erase(std::find_if(s.rbegin(), s.rend(), [](unsigned char ch) {
        return !std::isspace(ch);
    }).base(), s.end());
}

DebugConfig& DebugConfig::getInstance() {
    static DebugConfig instance;
    return instance;
}

DebugConfig::DebugConfig() {
    // Default constructor
}

void DebugConfig::load(const std::string& filepath) {
    config_data.clear();
    std::ifstream file(filepath);
    if (!file.is_open()) {
        std::cerr << "Warning: Could not open debug config file: " << filepath << std::endl;
        return;
    }

    std::cout << "--- DebugConfig::load START ---" << std::endl;
    std::string line;
    std::string current_section;
    while (std::getline(file, line)) {
        trim(line);
        std::cout << "Read line: '" << line << "'" << std::endl;
        if (line.empty() || line[0] == ';') {
            continue;
        }

        if (line[0] == '[' && line.back() == ']') {
            current_section = line.substr(1, line.length() - 2);
            trim(current_section);
            std::cout << "Set section to: '" << current_section << "'" << std::endl;
        } else {
            size_t equals_pos = line.find('=');
            if (equals_pos != std::string::npos) {
                std::string key = line.substr(0, equals_pos);
                trim(key);
                std::string value = line.substr(equals_pos + 1);
                trim(value);
                std::string full_key;
                if (!current_section.empty()) {
                    full_key = current_section + "." + key;
                } else {
                    full_key = key;
                }
                config_data[full_key] = value;
                std::cout << "Loaded config: '" << full_key << "' = '" << value << "'" << std::endl;
            }
        }
    }
    std::cout << "--- DebugConfig::load END ---" << std::endl;
}

bool DebugConfig::isEnabled(const std::string& key, bool default_value) const {
    auto it = config_data.find(key);
    if (it != config_data.end()) {
        std::string value = it->second;
        std::transform(value.begin(), value.end(), value.begin(), ::tolower);
        return value == "true" || value == "1" || value == "yes";
    }
    return default_value;
}